<template>
  <div id="global-header">
    <a-row flex="false">
      <a-col flex="200px"
        ><router-link to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/logo.png" alt="logo" />
            <div class="title">光点书集</div>
          </div>
        </router-link></a-col
      >
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        >
        </a-menu>
      </a-col>
      <a-col flex="120px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser?.id">
            <a-dropdown>
              <a-space>
                <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </a-space>
              <template #overlay>
                <a-menu>
                  <a-menu-item>
                    <UserOutlined />
                    <router-link to="/userInfo" style="padding-left: 8px">个人中心</router-link>
                  </a-menu-item>
                  <a-menu-item>
                    <IconFont type="icon-xitonggonggao" />
                    <router-link to="/systemAnnouncement" style="padding-left: 8px"
                      >系统公告</router-link
                    >
                  </a-menu-item>
                  <a-menu-item>
                    <a-popconfirm
                      title="确定要退出登录吗？"
                      @confirm="doLogout()"
                      okText="确定"
                      cancelText="取消"
                    >
                      <LogoutOutlined style="padding-right: 6px" />
                      退出登录
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { userLogoutUsingPost } from '@/api/userController'
import { BookOutlined, HomeOutlined, LogoutOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message, type MenuProps } from 'ant-design-vue'
import { computed, getCurrentInstance, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import AccessEnum from '../access/accessEnum'
import { useLoginUserStore } from '../stores/user'

const { appContext } = getCurrentInstance()!
const IconFont = appContext.components.IconFont
const current = ref<string[]>(['mail'])
const router = useRouter()
const loginUserStore = useLoginUserStore()

const menus = [
  { key: '/admin/data', label: '数据分析', title: '数据分析' },
  { key: '/', icon: h(HomeOutlined), label: '主页', title: '主页' },
  { key: '/admin/userManage', label: '用户管理', title: '用户管理' },
  { key: '/admin/bookManage', label: '图书管理', title: '图书管理' },
  { key: '/admin/recordManage', label: '借阅管理', title: '借阅管理' },
  { key: '/admin/announcementManage', label: '公告管理', title: '公告管理' },
  { key: '/my/recordBook', label: '我的借阅', icon: () => h(BookOutlined) },
  { key: '/my/recordHistory', label: '借阅历史', icon: () => h(BookOutlined) },
]

const doMenuClick = ({ key }: { key: string }) => {
  router.push(key)
}

router.afterEach((to) => {
  current.value = [to.path]
})

loginUserStore.fetchLoginUser()

const filterUserMenu = (menus: MenuProps['items'] = []) => {
  const loginUser = loginUserStore.loginUser
  if (!loginUser?.id) return menus.filter((menu) => menu.key === '/')
  return menus.filter((menu) => {
    if (menu.key.startsWith('/admin')) {
      return loginUser.userRole === AccessEnum.ADMIN
    }
    return true
  })
}

const filterAdminMenu = (menus: MenuProps['items'] = []) => {
  const loginUser = loginUserStore.loginUser
  if (!loginUser?.id) return menus.filter((menu) => menu.key === '/')

  return menus.filter((menu) => menu.key.startsWith('/admin'))
}

const items = computed<MenuProps['items']>(() => {
  const userRole = loginUserStore.loginUser?.userRole

  return userRole === AccessEnum.ADMIN ? filterAdminMenu(menus) : filterUserMenu(menus)
})

// 9. 退出登录
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  if (res.data.code === 0) {
    loginUserStore.loginUser = { userName: '未登录', userAvatar: '' }
    message.success('退出成功')
    router.push('/user/login')
  } else {
    message.error(res.data.message || '退出失败')
  }
}
</script>
<style lang="scss" scoped>
#global-header {
  .title-bar {
    display: flex;
    align-items: center;
    .logo {
      height: 48px;
    }
    .title {
      color: black;
      font-size: 18px;
      font-weight: bold;
      margin-left: 16px;
    }
  }
}
</style>
